package com.orange.controller.school;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.orange.controller.BaseController;
import com.orange.handler.AuthApplyFileService;
import com.orange.handler.AuthItemMapService;
import com.orange.handler.AuthSchoolService;
import com.orange.modules.bean.SessionUser;
import com.orange.modules.entity.AuthApplyFile;
import com.orange.modules.entity.manage.AuthSysDownload;
import com.orange.modules.entity.school.AuthSchool;
import com.orange.util.AppConfig;
import com.orange.util.ReturnCode;

@Controller
@RequestMapping("/applyFile")
public class AuthApplyFileController extends BaseController{

	private static final Logger logger = Logger.getLogger(AuthApplyFileController.class);
	
	@Autowired
	private AuthApplyFileService authApplyFileService;
	
	@Autowired
	private AuthSchoolService authSchoolService;
	
	@Autowired
	private AuthItemMapService authItemMapService;
	
	@Autowired
	private AppConfig appConfig;
	
	/**
	 * 数据填报  添加文件报告
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/insertApplyFile" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> insertApplyFile(HttpServletRequest request,@RequestBody Map<String ,String> map) throws SQLException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			
			String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			if(null==schoolId){
				return toResponse(null,ReturnCode.NOLOGIN,"未登录");
			}
			String subject=(String) request.getSession().getAttribute(SessionUser.SESSION_STATUS);
			
			String selfEvaluationFilepath = map.get("selfEvaluationFilepath");
			String selfEvaluationFilename = map.get("selfEvaluationFilename");
			String employmentDistributionFilepath = map.get("employmentDistributionFilepath");
			String employmentDistributionFilename = map.get("employmentDistributionFilename");
			String specialtyConstructionFilepath = map.get("specialtyConstructionFilepath");
			String specialtyConstructionFilename = map.get("specialtyConstructionFilename");
			String supportingMaterialsFilepath = map.get("supportingMaterialsFilepath");
			String supportingMaterialsFilename= map.get("supportingMaterialsFilename");
			/*if(selfEvaluationFilepath ==null || StringUtils.isBlank(selfEvaluationFilepath))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"自评报告路径不能为空!");
			if(selfEvaluationFilename ==null || StringUtils.isBlank(selfEvaluationFilename))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"自评报告名称不能为空!");
			if(employmentDistributionFilepath ==null || StringUtils.isBlank(employmentDistributionFilepath))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"近三年毕业生就业分布报告路径不能为空!");
			if(employmentDistributionFilename ==null || StringUtils.isBlank(employmentDistributionFilename))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"近三年毕业生就业分布报告名称不能为空!");
			if(specialtyConstructionFilepath ==null || StringUtils.isBlank(specialtyConstructionFilepath))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"专业建设与质量保障文件路径不能为空!");
			if(specialtyConstructionFilename ==null || StringUtils.isBlank(specialtyConstructionFilename))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"专业建设与质量保障文件名称不能为空!");
			if(supportingMaterialsFilepath ==null || StringUtils.isBlank(supportingMaterialsFilepath))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"学校认为的重要佐证材料路径不能为空!");
			if(supportingMaterialsFilename ==null || StringUtils.isBlank(supportingMaterialsFilename))
				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"学校认为的重要佐证材料名称不能为空!");*/
			AuthApplyFile aaf = authApplyFileService.queryAuthApplyFileBySchoolId(schoolId, subject);
			if(aaf==null){
				AuthApplyFile apf = new AuthApplyFile();
				apf.setCreatetime(sdf.format(new Date()));
				apf.setEmploymentDistributionFilename(employmentDistributionFilename);
				apf.setEmploymentDistributionFilepath(employmentDistributionFilepath);
				apf.setLogintype(subject);
				apf.setSelfEvaluationFilename(selfEvaluationFilename);
				apf.setSelfEvaluationFilepath(selfEvaluationFilepath);
				apf.setSid(schoolId);
				apf.setSpecialtyConstructionFilename(specialtyConstructionFilename);
				apf.setSpecialtyConstructionFilepath(specialtyConstructionFilepath);
				apf.setSupportingMaterialsFilename(supportingMaterialsFilename);
				apf.setSupportingMaterialsFilepath(supportingMaterialsFilepath);
				authApplyFileService.insertApplyFile(apf);
			}else{
				aaf.setEmploymentDistributionFilename(employmentDistributionFilename);
				aaf.setEmploymentDistributionFilepath(employmentDistributionFilepath);
				aaf.setSelfEvaluationFilename(selfEvaluationFilename);
				aaf.setSelfEvaluationFilepath(selfEvaluationFilepath);
				aaf.setSpecialtyConstructionFilename(specialtyConstructionFilename);
				aaf.setSpecialtyConstructionFilepath(specialtyConstructionFilepath);
				aaf.setSupportingMaterialsFilename(supportingMaterialsFilename);
				aaf.setSupportingMaterialsFilepath(supportingMaterialsFilepath);
				authApplyFileService.insertApplyFile(aaf);
			}
			return toResponse(aaf,ReturnCode.SUCCESS,"新增成功");
		}catch(Exception e){
			logger.error("新增失败",e);
			return toResponse(null,ReturnCode.FAIL,"新增失败");
		}
		
		
	}
	
	/**
	 * 根据该用户查询是否提交过数据
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryApplyFileBySchoolId" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> queryApplyFileBySchoolId(HttpServletRequest request,@RequestBody Map<String ,String> map) throws SQLException{
		
		try {
			String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			if(null==schoolId){
				return toResponse(null,ReturnCode.NOLOGIN,"未登录");
			}
			String subject=(String) request.getSession().getAttribute(SessionUser.SESSION_STATUS);
			AuthApplyFile aaf = authApplyFileService.queryAuthApplyFileBySchoolId(schoolId, subject);
			return toResponse(aaf,ReturnCode.SUCCESS,"查询成功");
		} catch (Exception e) {
			logger.error("查询失败",e);
			return toResponse(null,ReturnCode.FAIL,"查询失败");
		}
		
	}
	
	/**
	 * 提交申请
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/submitApplyFile" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> submitApplyFile(HttpServletRequest request,@RequestBody Map<String ,String> map) throws SQLException{
		
		try {
			String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			if(null==schoolId){
				return toResponse(null,ReturnCode.NOLOGIN,"未登录");
			}
			AuthSchool a=authSchoolService.queryAuthSchoolInfoById(schoolId);
			if(null==a){
				return toResponse(null,ReturnCode.USERINFO_NOT_EXIST,"该机构信息不存在");
			}
			if(!"0".equals(a.getState())){
				return toResponse(null,ReturnCode.SCHOOL_SUBMIT_HAVE,"学校已提交申请不可重复提交");
			}
			//a.setState("1");
			String subject=(String) request.getSession().getAttribute(SessionUser.SESSION_STATUS);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				
			String selfEvaluationFilepath = map.get("selfEvaluationFilepath");
			String selfEvaluationFilename = map.get("selfEvaluationFilename");
			String employmentDistributionFilepath = map.get("employmentDistributionFilepath");
			String employmentDistributionFilename = map.get("employmentDistributionFilename");
			String specialtyConstructionFilepath = map.get("specialtyConstructionFilepath");
			String specialtyConstructionFilename = map.get("specialtyConstructionFilename");
			String supportingMaterialsFilepath = map.get("supportingMaterialsFilepath");
			String supportingMaterialsFilename= map.get("supportingMaterialsFilename");
			AuthApplyFile aaf = authApplyFileService.queryAuthApplyFileBySchoolId(schoolId, subject);
			if(aaf==null){
				AuthApplyFile apf = new AuthApplyFile();
				apf.setCreatetime(sdf.format(new Date()));
				apf.setEmploymentDistributionFilename(employmentDistributionFilename);
				apf.setEmploymentDistributionFilepath(employmentDistributionFilepath);
				apf.setLogintype(subject);
				apf.setSelfEvaluationFilename(selfEvaluationFilename);
				apf.setSelfEvaluationFilepath(selfEvaluationFilepath);
				apf.setSid(schoolId);
				apf.setSpecialtyConstructionFilename(specialtyConstructionFilename);
				apf.setSpecialtyConstructionFilepath(specialtyConstructionFilepath);
				apf.setSupportingMaterialsFilename(supportingMaterialsFilename);
				apf.setSupportingMaterialsFilepath(supportingMaterialsFilepath);
				authApplyFileService.insertApplyFile(apf);
			}else{
				aaf.setEmploymentDistributionFilename(employmentDistributionFilename);
				aaf.setEmploymentDistributionFilepath(employmentDistributionFilepath);
				aaf.setSelfEvaluationFilename(selfEvaluationFilename);
				aaf.setSelfEvaluationFilepath(selfEvaluationFilepath);
				aaf.setSpecialtyConstructionFilename(specialtyConstructionFilename);
				aaf.setSpecialtyConstructionFilepath(specialtyConstructionFilepath);
				aaf.setSupportingMaterialsFilename(supportingMaterialsFilename);
				aaf.setSupportingMaterialsFilepath(supportingMaterialsFilepath);
				authApplyFileService.insertApplyFile(aaf);
			}
			if("1101".equals(subject)){  //理科
				a.setScience("1");
			}else if("1102".equals(subject)){  //文科
				a.setLiberalarts("1");
			}else if("1103".equals(subject)){  //整体申报
				a.setWholeDeclaration("1");
			}
			authSchoolService.updateAuthSchoolInfo(a);
			
			
			return toResponse(aaf,ReturnCode.SUCCESS,"提交申请成功");
		} catch (Exception e) {
			logger.error("提交申请失败",e);
			return toResponse(null,ReturnCode.FAIL,"提交申请失败");
		}
		
	}
	/*********************************************************************************************************************/
	
	/**
	 * 根据该用户查询是否提交过数据
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryApplyFileBySchoolId1" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET
			)
	@ResponseBody
	public ResponseEntity<String> queryApplyFileBySchoolId1(HttpServletRequest request,@RequestParam String schoolid) throws SQLException{
		try {			
			AuthApplyFile aaf = authApplyFileService.queryAuthApplyFileBySchoolId(schoolid, null);
			return toResponse(aaf,ReturnCode.SUCCESS,"查询成功");
		} catch (Exception e) {
			logger.error("查询失败",e);
			return toResponse(null,ReturnCode.FAIL,"查询失败");
		}
		
	}
	/**
	 * 下载文档
	 */
	@RequestMapping(value="/downloadApplyFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public void downloadApplyFile(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid,@RequestParam String number){
		try {
			AuthApplyFile a = authApplyFileService.queryApplyFileById(pid);
			if(null==a){
				return;
			}
			//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
	        String path = appConfig.getFilePath();  
	        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
	        response.setContentType("multipart/form-data");  
	        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf) 
	        String filepath1= a.getSelfEvaluationFilepath();
	        String filepath2= a.getEmploymentDistributionFilepath();
	        String filepath3= a.getSpecialtyConstructionFilepath();
	        String filepath4= a.getSupportingMaterialsFilepath();
	        if("1".equals(number)){
	        	String filename=filepath1.substring(filepath1.lastIndexOf("/")+1, filepath1.length());
	 	        response.setHeader("Content-Disposition", "inline; filename="  
	 	                + new String(filename.getBytes("utf-8"), "ISO-8859-1"));  
	 	        ServletOutputStream out;  
	 	        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
	 	        File file = new File(path +filepath1);  
	 	  
 	            FileInputStream inputStream = new FileInputStream(file);  
 	  
 	            //3.通过response获取ServletOutputStream对象(out)  
 	            out = response.getOutputStream();  
 	            
 	            byte[] buffer = new byte[512];  
 	            int count = 0;
 		         while ((count = inputStream.read(buffer)) > 0) {
 		        	 out.write(buffer, 0, count);
 		         }
 	            inputStream.close();  
 	            out.close();  
 	            out.flush();  
	        }else if("2".equals(number)){
	        	String filename=filepath2.substring(filepath2.lastIndexOf("/")+1, filepath2.length());
	 	        response.setHeader("Content-Disposition", "inline; filename="  
	 	                + new String(filename.getBytes("utf-8"), "ISO-8859-1"));  
	 	        ServletOutputStream out;  
	 	        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
	 	        File file = new File(path +filepath2);  
	 	  
 	            FileInputStream inputStream = new FileInputStream(file);  
 	  
 	            //3.通过response获取ServletOutputStream对象(out)  
 	            out = response.getOutputStream();  
 	            
 	            byte[] buffer = new byte[512];  
 	            int count = 0;
 		         while ((count = inputStream.read(buffer)) > 0) {
 		        	 out.write(buffer, 0, count);
 		         }
 	            inputStream.close();  
 	            out.close();  
 	            out.flush();  
	        }else if("3".equals(number)){
	        	String filename=filepath3.substring(filepath3.lastIndexOf("/")+1, filepath3.length());
	 	        response.setHeader("Content-Disposition", "inline; filename="  
	 	                + new String(filename.getBytes("utf-8"), "ISO-8859-1"));  
	 	        ServletOutputStream out;  
	 	        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
	 	        File file = new File(path +filepath3);  
	 	  
 	            FileInputStream inputStream = new FileInputStream(file);  
 	  
 	            //3.通过response获取ServletOutputStream对象(out)  
 	            out = response.getOutputStream();  
 	            
 	            byte[] buffer = new byte[512];  
 	            int count = 0;
 		         while ((count = inputStream.read(buffer)) > 0) {
 		        	 out.write(buffer, 0, count);
 		         }
 	            inputStream.close();  
 	            out.close();  
 	            out.flush();  
	        }else{
	        	String filename=filepath4.substring(filepath4.lastIndexOf("/")+1, filepath4.length());
	 	        response.setHeader("Content-Disposition", "inline; filename="  
	 	                + new String(filename.getBytes("utf-8"), "ISO-8859-1"));  
	 	        ServletOutputStream out;  
	 	        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
	 	        File file = new File(path +filepath4);  
	 	  
 	            FileInputStream inputStream = new FileInputStream(file);  
 	  
 	            //3.通过response获取ServletOutputStream对象(out)  
 	            out = response.getOutputStream();  
 	            
 	            byte[] buffer = new byte[512];  
 	            int count = 0;
 		         while ((count = inputStream.read(buffer)) > 0) {
 		        	 out.write(buffer, 0, count);
 		         }
 	            inputStream.close();  
 	            out.close();  
 	            out.flush();  
	        }
	       
	  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
